package cs.uns.edu.ar.aygps.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;

import cs.uns.edu.ar.aygps.model.exception.AyGPSException;

public class ConnectionFactory {
	
	private static ConnectionFactory instance;
	private static DataSource ds;
	
	private ConnectionFactory(){
		try {
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

			final GenericObjectPool pool = new GenericObjectPool(null);
			final PoolableConnectionFactory cf = new PoolableConnectionFactory(new DriverManagerConnectionFactory("jdbc:derby:/AyGPS/AyGPS-Data/db;create=true", "app",
					""), pool, null, "SELECT 0 FROM SYSIBM.SYSDUMMY1", false, true);
			pool.setFactory(cf);
			pool.setMaxActive(-1);
			pool.setMaxIdle(-1);
			pool.setTestOnBorrow(true);
			pool.setTestWhileIdle(true);

			ds = new PoolingDataSource(pool);
		} catch (Exception e) {
			throw new RuntimeException("Cannot create datasource object for database AYGPS.", e);
		}
	}
	
	public static ConnectionFactory getInstance(){
		if (instance == null){
			instance = new ConnectionFactory();
		}
		return instance;
	}
	
	public Connection getConnection() throws SQLException{
			Connection conn = ds.getConnection();
			conn.setAutoCommit(true);
			return conn;
	}

}
